#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/10 15:12
# @File    : test.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn
import asyncio

from fastapi import FastAPI, BackgroundTasks, Depends
from threading import Thread
import time

app = FastAPI()


def background_task(end=10):
    i = 0
    print("开始任务")
    while i <= end:
        # 模拟一个长时间运行的任务
        print(f"{i} This is a background task running in a separate thread.")
        time.sleep(1)  # 让线程休眠一秒，以避免忙等待
        i += 1
    print("任务完成")


@app.on_event("startup")
async def startup_event():
    # 在应用启动时启动一个后台线程
    thread = Thread(target=background_task, daemon=True)  # 设置为守护线程
    #thread.start()


@app.post("/send-email")
async def send_email(email_data: dict, background_tasks: BackgroundTasks):
    # 执行一些即时返回给客户端的操作
    # ...

    # 安排后台任务
    #background_tasks.add_task(send_email_task, email_data)
    background_tasks.add_task(background_task, 15)

    return {"message": "Email sending task scheduled in the background"}


async def send_email_task(email_data):
    # 这里是发送电子邮件的逻辑
    # 注意：这个函数应该是异步的，并使用异步库进行通信
    await asyncio.sleep(5)  # 模拟发送电子邮件的耗时操作
    print(f"Email sent with data: {email_data}")


@app.get("/")
async def read_root():
    return {"message": "Hello, World! The background task is running in a separate thread."}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8001)